package com.atguigu.flink0922.chapter11;

import com.atguigu.flink0922.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/10 10:20
 */
public class Flink01_Table_BaseUser {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
    
        DataStreamSource<WaterSensor> waterSensorStream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 2000L, 20),
                             new WaterSensor("sensor_2", 3000L, 30),
                             new WaterSensor("sensor_1", 4000L, 40),
                             new WaterSensor("sensor_1", 5000L, 50),
                             new WaterSensor("sensor_2", 6000L, 60));
    
        // 1. 先创建table执行环境
        final StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        // 2. 根据流创建动态表
        final Table table = tenv.fromDataStream(waterSensorStream);
        // 3. 在动态表上执行连续查询
        // select id as a from t where id=...
        final Table resultTable = table
            .where($("id").isEqual("sensor_1"))
            .select($("id"), $("ts"), $("vc"));
        // 4. 把查询的结果(动态表)转成流输出
        final DataStream<WaterSensor> ds = tenv.toAppendStream(resultTable, WaterSensor.class);
        ds.print();
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
